import { useEffect } from 'react'

import { getCitiesTreeApi } from '@/api/pcs/cities'
import { createCommodityApi, updateCommodityApi } from '@/api/pcs/commodity'
import { hospitalAndAreaTreeApi } from '@/api/pcs/pcsHospital'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { BOOLEAN_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

const EditModal = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const homeDelivery = AekForm.useWatch('homeDelivery', form)
  const hospitalDelivery = AekForm.useWatch('hospitalDelivery', form)
  const { id } = row

  useEffect(() => {
    form.setFieldsValue({
      homeDelivery: BOOLEAN_ENUM.FALSE,
      hospitalDelivery: BOOLEAN_ENUM.FALSE,
    })
    if (!id) return
    form.setFieldsValue({
      ...row,
      homeDelivery: row.homeDelivery === 1 || BOOLEAN_ENUM.FALSE,
      addressScope: row.addressScope ? JSON.parse(row.addressScope) : [],
      hospitalDelivery: row.hospitalDelivery === 1 || BOOLEAN_ENUM.FALSE,
      hospitalScope: row.hospitalScope ? JSON.parse(row.hospitalScope) : [],
    })
  }, [id])

  const getHospitalAndAreaTree = async () => {
    const _hospitalAndAreaTree = []
    const { data } = await requestWithTry(hospitalAndAreaTreeApi)
    data.forEach(item => {
      const { areaInfos } = item
      areaInfos.forEach(childItem => {
        _hospitalAndAreaTree.push({
          id: +childItem.id,
          name: `${item.name}/${childItem.name}`,
        })
      })
    })
    return { data: _hospitalAndAreaTree }
  }

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'commodityName',
      label: '商品名称',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Input',
        props: {
          disabled: row.id,
        },
      },
    },
    {
      field: 'commodityModel',
      label: '规格型号',
      component: {
        name: 'Input',
        props: {
          disabled: row.id,
        },
      },
    },
    {
      field: 'unit',
      label: '单位',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      field: 'price',
      label: '单价',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekInputNumber',
        props: {
          min: 0,
          step: 0.01,
          precision: 2,
        },
      },
    },
    {
      field: 'commodityImage',
      label: '商品主图',
      formItemProps: {
        rules: [{ required: true }],
        help: '限png格式，大小40x40',
      },
      component: { name: 'AekUpload', props: { fileType: 'img', listType: 'picture-card', limitFileNum: 1 } },
    },
    {
      field: 'brand',
      label: '品牌',
      component: { name: 'Input' },
    },
    {
      field: 'manufacturer',
      label: '厂家',
      component: { name: 'Input' },
    },
    {
      field: 'homeDelivery',
      label: '居家配送',
      component: { name: 'RadioGroup', props: { options: BOOLEAN_ENUM.options } },
    },
    {
      exclude: !homeDelivery,
      field: 'addressScope',
      label: '区域范围',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekTreeSelect',
        props: {
          api: getCitiesTreeApi,
          treeCheckable: true,
        },
      },
    },
    {
      field: 'hospitalDelivery',
      label: '院内配送',
      component: { name: 'RadioGroup', props: { options: BOOLEAN_ENUM.options } },
    },
    {
      exclude: !hospitalDelivery,
      field: 'hospitalScope',
      label: '医院范围',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          api: getHospitalAndAreaTree,
          mode: 'multiple',
        },
      },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      id,
      ...values,
      homeDelivery: +values.homeDelivery,
      hospitalDelivery: +values.hospitalDelivery,
      commodityImage: values.commodityImage?.map(({ url }) => url).join(','),
    }
    await requestWithTry(id ? updateCommodityApi : createCommodityApi, params)
  }
  return (
    <AekModal title={id ? '编辑' : '新增'} width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

EditModal.PromiseThen = PromiseThen

export default EditModal
